<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * 门店商品群组模型
 * 
 * @property int $id 主键
 * @property string $group_name 群组名称
 * @property int $province_id 省ID
 * @property int $city_id 市ID
 * @property int $district_id 区ID
 * @property int $type_id 归属分类
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 */
class StoreProductGroup extends Model
{
    /**
     * 表名
     */
    protected $table = 'ims_yz_store_product_groups';

    /**
     * 主键
     */
    protected $primaryKey = 'id';

    /**
     * 可批量赋值的属性
     */
    protected $fillable = [
        'group_name',
        'province_id',
        'city_id',
        'district_id',
        'type_id',
    ];

    /**
     * 属性类型转换
     */
    protected $casts = [
        'id' => 'integer',
        'province_id' => 'integer',
        'city_id' => 'integer',
        'district_id' => 'integer',
        'type_id' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * 关联：群组包含的商品
     */
    public function products()
    {
        return $this->hasMany(StoreProductGroupProduct::class, 'group_id', 'id');
    }

    /**
     * 关联：群组分类
     */
    public function category()
    {
        return $this->belongsTo(Category::class, 'type_id', 'id');
    }

    /**
     * 关联：省份
     */
    public function province()
    {
        return $this->belongsTo(Address::class, 'province_id', 'id');
    }

    /**
     * 关联：城市
     */
    public function city()
    {
        return $this->belongsTo(Address::class, 'city_id', 'id');
    }

    /**
     * 关联：区县
     */
    public function district()
    {
        return $this->belongsTo(Address::class, 'district_id', 'id');
    }

    /**
     * 根据地域和类型查询群组
     */
    public function scopeByLocationAndType($query, $provinceId, $cityId, $districtId, $typeId = null)
    {
        $query->where('province_id', $provinceId)
              ->where('city_id', $cityId)
              ->where('district_id', $districtId);
              
        if ($typeId !== null) {
            $query->where('type_id', $typeId);
        }
        
        return $query;
    }

    /**
     * 根据地域查询群组
     */
    public function scopeByLocation($query, $provinceId, $cityId, $districtId)
    {
        return $query->byLocationAndType($provinceId, $cityId, $districtId);
    }
}
